﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

using VirtualTournaments.DataAccess.SqlServer.DataMappers;

namespace VirtualTournaments.DataAccess.SqlServer.DataProxies
{
	internal sealed class TournamentPodiumBetTargetDataProxy : Business.Bets.TournamentPodiumBetTarget, IDataProxy<SqlServer.TournamentPodiumBetTarget>, Identifiable<SqlServer.TournamentPodiumBetTarget>
	{
		internal TournamentPodiumBetTargetDataProxy(SqlServer.TournamentPodiumBetTarget dataObject)
			: base(null, null)
		{
			InnerDataObject = dataObject;
			MapProperties();
		}

		#region Override properties

		internal bool BetsHasBeenRead { get; set; }
		public override IList<Business.Bets.Bet> Bets
		{
			get
			{
				if (!BetsHasBeenRead)
				{
					BetsHasBeenRead = true;
					if (base.Bets == null)
					{
						base.Bets = MapBets();
					}
				}
				return base.Bets;
			}
		}

		internal bool TournamentHasBeenRead { get; set; }
		public override Business.Tournaments.Tournament Tournament
		{
			get
			{
				if (!TournamentHasBeenRead)
				{
					TournamentHasBeenRead = true;
					if (base.Tournament == null)
					{
						base.Tournament = MapTournament();
					}
				}
				return base.Tournament;
			}
		}

		internal bool PodiumHasBeenRead { get; set; }
		public override Business.Bets.Podium Podium
		{
			get
			{
				if (!PodiumHasBeenRead)
				{
					PodiumHasBeenRead = true;
					if (base.Podium == null)
					{
						base.Podium = MapPodium();
					}
				}
				return base.Podium;
			}
		}

		#endregion

		#region Mapping methods

		private void MapProperties()
		{
			this.Bets = null;
			this.Odds = Convert.ToDecimal(InnerDataObject.BetTarget.Odds);
		}

		private Business.Tournaments.Tournament MapTournament()
		{
			return AllAgainstAllTournamentsDataMapper.Instance.DataObject2BusinessObject(InnerDataObject.Tournament);
		}

		private Business.Bets.Podium MapPodium()
		{
			return new PodiumDataProxy(InnerDataObject);
		}

		private IList<Business.Bets.Bet> MapBets()
		{
			return InnerDataObject.BetTarget.BetTargetBets.Select(betTargetBet => BetsDataMapper.Instance.DataObject2BusinessObject(betTargetBet.Bet)).ToList();
		}

		#endregion

		#region IDataProxy<TournamentPodiumBetTarget> Members

		public SqlServer.TournamentPodiumBetTarget InnerDataObject { get; set; }

		#endregion

		#region Identifiable<TournamentPodiumBetTarget> Members

		public Expression<Func<SqlServer.TournamentPodiumBetTarget, bool>> GetUniqueWhereExpression()
		{
			throw new System.NotImplementedException();
		}

		#endregion
	}
}
